import commonjs from '@rollup/plugin-commonjs'
import { nodeResolve } from '@rollup/plugin-node-resolve'
import { terser } from 'rollup-plugin-terser'
import serve from 'rollup-plugin-serve'
import livereload from 'rollup-plugin-livereload'
import postcss from 'rollup-plugin-postcss'
import autoprefixer from 'autoprefixer'
// import typescript from 'rollup-plugin-typescript2'
import json from '@rollup/plugin-json'
import babel from '@rollup/plugin-babel'
import dotenv from 'dotenv'
import replace from '@rollup/plugin-replace'

import path from 'path'
import packageJSON from './package.json'

const __dirname = path.resolve()
// load env
dotenv.config()
// const diy = process.env.diy
// const envPath = path.resolve(__dirname, `.env${diy ? `.${diy}` : ``}`)
// dotenv.config({ path: envPath })
// console.log(import.meta)
// console.log(process.env)

const mode = process.env.mode
const rollup = mode === 'serve' ? 
  {
    input: 'src/main.js',
    external: ['react', 'react-dom'],
    // external: ['antd'],
    // external: [],
    context: 'null',
    moduleContext: 'null',
    output: [
      {
        file: 'dist/serve.js',
        format: 'es',
        globals: {
          raact: 'React',
          'react-dom': 'ReactDOM',
          antd: 'antd'
        }
      }
    ],
    plugins: [
      nodeResolve({
        jsnext: true,
        main: true,
        browser: true
      }),
      replace({
        preventAssignment: true,
        'process.env.NODE_ENV': JSON.stringify('development')
      }),
      // typescript(),
      json(),
      babel({
        presets: ["@babel/preset-env"],
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        babelHelpers: 'runtime',
        'plugins':["@babel/plugin-transform-runtime"],
        exclude: '**/node_modules/**'
      }),
      terser(),
      // postcss({
      //   plugins: [
      //     autoprefixer()
      //   ]
      // }),
      // dotenv(),
      commonjs(),
      livereload({
        watch: 'dist/serve.js',
        verbose: false
      }),
      serve({
        port: 8888,
        contentBase: ['', 'public'],
        historyApiFallback: '/404.html',
        verbose: false
      })
    ]
  } : 
  {
    input: 'src/ui.js',
    external: ['react', 'react-dom', 'lodash'],
    output: [
      {
        file: `dist/${packageJSON.name}@${packageJSON.version}/index.js`,
        format: 'system',
        sourcemap: false
      },
      // {
      //   file: `dist/${packageJSON.name}@${packageJSON.version}/index.min.js`,
      //   format: 'esm',
      //   sourcemap: false,
      //   plugins: [
      //     terser()
      //   ]
      // }
    ],
    plugins: [
      nodeResolve({
        extensions: ['.js'],
      }),
      babel({
        presets: ["@babel/preset-react"],
        babelHelpers: 'bundled'
      }),
      commonjs()
    ]
  }

export default rollup
